#!/bin/bash


# ATTENTION: il n'importe PAS les variables de generate_configuration.sh !!!

# 2012-07-12 12:57:33+03:00 192.168.0.5 in_traffic 1368
# 2012-07-12 12:57:33+03:00 192.168.0.6 in_traffic 1368
# 2012-07-12 12:57:33+03:00 192.168.0.7 in_traffic 0
# 2012-07-12 12:57:33+03:00 192.168.0.8 in_traffic 4953298

export NOW=$(date --rfc-3339=sec); 

rm -f /tmp/all_traffic
rm -f /tmp/in_traffic
rm -f /tmp/out_traffic

for IP_DU_LAN in $(awk '{print $4}' < /tmp/users)
# for IP_DU_LAN in $(/usr/bin/prips 192.168.0.0/24)
do
    IP_UNDERSCORE=$(echo ${IP_DU_LAN} | sed 's/\./_/g') 
    CHAIN_IN="acct_in_"${IP_UNDERSCORE}
    CHAIN_OUT="acct_out_"${IP_UNDERSCORE}

    /sbin/iptables -t filter -L ${CHAIN_IN} -v -n -x \
        | awk -v date="${NOW}" -v iplan="${IP_DU_LAN}" '/ RETURN/{print date, iplan, "in_traffic", $2;}' >> /tmp/all_traffic
    /sbin/iptables -t filter -L ${CHAIN_OUT} -v -n -x \
        | awk -v date="${NOW}" -v iplan="${IP_DU_LAN}" '/ RETURN/{print date, iplan, "out_traffic", $2;}' >> /tmp/all_traffic

done

while read DATE TIME IP TABLE VALUE
do 
    GUY=$(dig -t PTR +short $(echo ${IP} | awk -F "." '{for (i=NF;i>=1;i--) printf $i"."; print "in-addr.arpa."}') | awk -F '.' '{print $1}')
    if [ "${GUY}" != "" ]
    then 
        echo "INSERT INTO ${TABLE} (date, time, name, traffic) VALUES ('${DATE}',  '${TIME}',  '${GUY}', ${VALUE});" | mysql -u bwstat -p5o1VO backteam_bwstat 
    fi
done <  /tmp/all_traffic
